package com.handpay.zztong.hp;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.main.fragment.ReceivablesFragment;
import com.handpay.framework.utils.BitmapLoaderNew;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.paymentbill.model.Bill;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.paymentbill.activity.TransResultFailureActivity;
import com.handpay.zztong.hp.paymentbill.activity.TransResultSuccessActivity;
import com.handpay.zztong.hp.trans.activity.VPOSActivity;
import com.nostra13.universalimageloader.core.assist.FailReason;

import org.apache.http.HttpStatus;

import java.text.DecimalFormat;
import java.util.Hashtable;

import se.krka.kahlua.vm.LuaTable;

/***
 * @author sxshi
 *  原始微信正扫支付 包含关闭订单，获取支付结果超时，等。
 *  @deprecated  use{@link ScannerCodePayActivity }instead
 */
@Deprecated
public class ScanQrCodeActivity extends ZZTongActivity {
    private String mQrCodeUrl;
    private String mOrderNo;
    private double amount;
    private String mToken;
    private String mPayOrderID;
    private ImageView iv_qrcode;
    private TextView tv_amount;
    private Button btn_jump_customer;
    private Button btn_close_order;
    private Runnable resultRunnable = null;
    private boolean isJumpCustomer = false;
    private Handler mHamder = null;
    public static final String billvalue = "bill";
    private int tradeType = 4;
    private boolean isOpenWechatPayScan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_scan_qr_code);
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        mQrCodeUrl = intent.getStringExtra("mQrCodeUrl");
        mOrderNo = intent.getStringExtra("mOrderNo");
        amount = intent.getDoubleExtra("amount", 0);
        tradeType = intent.getIntExtra("tradeType", 4);
        mToken = intent.getStringExtra("token");
        mPayOrderID = intent.getStringExtra("payOrderID");
        isOpenWechatPayScan = intent.getBooleanExtra("isOpenWechatPayScan", false);
        mHamder = new Handler();
        initView();
        initData();
        if (amount > 0) tv_amount.setText(String.format("¥%s", fromatMoney(amount)));
        BitmapLoaderNew.getInstance(this).loadImage(mQrCodeUrl, new BitmapLoaderNew.BitmapLoaderListener() {
            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                iv_qrcode.setImageBitmap(bitmap);
                getTransResult();
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                showAlertDialog(ScanQrCodeActivity.this, "", "微信二维码加载失败！", false, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                        dialogInterface.dismiss();
                    }
                });
            }
        });
        initListener();
    }

    private void initData() {
        resultRunnable = new Runnable() {
            @Override
            public void run() {
                Hashtable<String, String> param = new Hashtable<String, String>();
                param.put("payOrderID", mPayOrderID);
                doPost(true, ScanQrCodeActivity.this, ZZTongActivity.Do_QueryQrCodeTransferResult, param, false, null, 120 * 1000);
            }
        };
    }

    /***
     * Generate QR codes
     *
     * @param url
     * @return
     */
    @Deprecated
    private Bitmap generateQRCode(String url) {
        try {
            QRCodeWriter writer = new QRCodeWriter();
            // MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix matrix = writer.encode(mQrCodeUrl, BarcodeFormat.QR_CODE, 1000, 1000);
            return bitMatrix2Bitmap(matrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Bitmap bitMatrix2Bitmap(BitMatrix matrix) {
        int w = matrix.getWidth();
        int h = matrix.getHeight();
        int[] rawData = new int[w * h];
        for (int i = 0; i < w; i++) {
            for (int j = 0; j < h; j++) {
                int color = Color.WHITE;
                if (matrix.get(i, j)) {
                    color = Color.BLACK;
                }
                rawData[i + (j * w)] = color;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        bitmap.setPixels(rawData, 0, w, 0, 0, w, h);
        return bitmap;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        btn_close_order = (Button) findViewById(R.id.btn_close_order);
        btn_jump_customer = (Button) findViewById(R.id.btn_jump_customer);
        tv_amount = (TextView) findViewById(R.id.tv_hint_amount);
        iv_qrcode = (ImageView) findViewById(R.id.iv_qrcode);
    }

    private void initListener() {
        btn_jump_customer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isJumpCustomer = true;
                cancelVolleyRequest(ZZTongActivity.Do_QueryQrCodeTransferResult);
                mHamder.removeCallbacks(resultRunnable);
                closeOrder();
            }
        });
        btn_close_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cancelVolleyRequest(ZZTongActivity.Do_QueryQrCodeTransferResult);
                mHamder.removeCallbacks(resultRunnable);
                closeOrder();
            }
        });
    }

    @Override
    public ActionBar getActivityActionBar() {
        ImageButton imageButton = new ImageButton(this);
        imageButton.setBackgroundResource(R.drawable.help);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.rightMargin = 20;
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("type", ZZTConstant.WETCHAT_MERCHANT);
                intent.setClass(ScanQrCodeActivity.this, HelpWechatPayActivity.class);
                startActivity(intent);
            }
        });
        return new ActionBar(this.getString(R.string.capture_title_merchant), true, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeOrder();
            }
        }, imageButton, layoutParams);
    }

    /***
     * @param number
     * @return p
     */
    private String fromatMoney(Double number) {
        double amV = (number / 100.00);
        DecimalFormat decimalFormat = new DecimalFormat(".00");
        String p = decimalFormat.format(amV);
        //这里暂时这么写当收款金额为0.01   p经过转换后变成 .01
        if (p != null && p.contains(".") && p.substring(0, 1).equals(".")) {
            p = "0" + p;
        }
        return p;
    }

    @Override
    public boolean netResponse(final String action, Hashtable<String, Object> resp, boolean showAlert) {
        int respCode = (Integer) resp.get(HttpEngine.Key_RespCode);
        String errMsg = (String) resp.get(HttpEngine.Key_RespErrMsg);
        byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
        if (respCode == HttpStatus.SC_NOT_FOUND) {
            this.showAlertDialog(this, getString(R.string.hint_conn_err), errMsg, false, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            });
            return true;
        } else if (respCode == HttpStatus.SC_SERVICE_UNAVAILABLE) {
            this.showAlertDialog(this, getString(R.string.hint_server_error), errMsg, false, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            });
            return true;
        } else if (respCode == HttpStatus.SC_UNAUTHORIZED) {
            this.showAlertDialog(this, getString(R.string.hint_author_error), errMsg, false, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            });
            return true;
        } else if (respCode == HttpStatus.SC_REQUEST_TIMEOUT) {
            if (action.equals(ZZTongActivity.Do_QrCodeTransferClose)) {
                this.showAlertDialog(this, "", getString(R.string.hint_order_timeout_msg), false, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
            } else if (action.equals(ZZTongActivity.Do_QueryQrCodeTransferResult)) {
                Bill bill = new Bill();
                bill.setTransTime(" ");
                bill.setTransStatus("交易超时");
                bill.setStatus(0);
                bill.setTransAccount(" ");
                bill.setTransSN(" ");
                bill.setOrderNo(mOrderNo);
                bill.setShopName(" ");
                bill.setAmount(amount);
                bill.setTradeType(tradeType);
                Intent intent = new Intent(this, TransResultFailureActivity.class);
                intent.putExtra(billvalue, bill);
                intent.putExtra(PAYTYPE, tradeType);
                startActivity(intent);
                this.finish();
            }
            return true;
        }
        LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
        if (luaTable == null) {
            this.closeProgressDialog();
            this.showAlertDialog(this, "" + respCode, "返回数据有误，请稍后再试。", true, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            });
            return true;
        } else {
            String errMessage = (String) luaTable.rawget("errMessage");
            if (!TextUtils.isEmpty(errMessage)) {
                this.closeProgressDialog();
                this.showAlertDialog(this, null, errMessage, false, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                        dialogInterface.dismiss();
                    }
                });
            } else {
                if (action.equals(ZZTongActivity.Do_QrCodeTransferClose)) {
                    this.closeProgressDialog();
                    String status = luaTable.rawget("status").toString();
                    String message = luaTable.rawget("message").toString();
                    if (!TextUtils.isEmpty(status) && "1".equals(status)) {
                        if (isJumpCustomer) {
                            Hashtable<String, Object> params = new Hashtable<String, Object>();
                            params.put(ZZTongActivity.ACTION, ZZTongActivity.Action_Transfer1);
                            params.put(VPOSActivity.Transfer_Amount_Key, amount);
                            params.put(ZZTongActivity.PAYTYPE, ReceivablesFragment.PAY_TYPE_WECHATPAY);
                            params.put("isOpenWechatPayScan", isOpenWechatPayScan);
                            startActivity(ScanQrCodeActivity.this, WebPayWaitingResultActivity.class, params);
                            finish();
                        } else {
                            Toast.makeText(ScanQrCodeActivity.this, getString(R.string.hint_closed_order), Toast.LENGTH_SHORT).show();
                            finish();
                        }
                        return false;
                    } else {
                        this.showAlertDialog(this, "", message, false, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                finish();
                                dialogInterface.dismiss();
                            }
                        });
                        return true;
                    }
                } else if (action.equals(ZZTongActivity.Do_QueryQrCodeTransferResult)) {
                    this.closeProgressDialog();
                    Bill bill = CommonUtils.generateBill(luaTable, Bill.APPCODE.TRANS);
                    HPLog.i(HPLog.SSX_TAG, bill.toString());
                    if (bill.getStatus() == 1) {
                        Intent intent = new Intent(this, TransResultSuccessActivity.class);
                        intent.putExtra(billvalue, bill);
                        intent.putExtra(PAYTYPE, tradeType);
                        intent.putExtra(ACTION, this.mAction);
                        startActivity(intent);
                        this.finish();
                    } else {
                        Intent intent = new Intent(this, TransResultFailureActivity.class);
                        intent.putExtra(billvalue, bill);
                        intent.putExtra(PAYTYPE, tradeType);
                        startActivity(intent);
                        this.finish();
                    }
                    return false;
                }
            }
        }
        return false;
    }

    /***
     * Closed orders
     */
    private void closeOrder() {
        cancelVolleyRequest(ZZTongActivity.Do_QueryQrCodeTransferResult);
        mHamder.removeCallbacks(resultRunnable);
        Hashtable<String, String> param = new Hashtable<String, String>();
        param.put("orderNo", mOrderNo);
        param.put("token", mToken);
        param.put("payOrderID", mPayOrderID);
        doPost(true, this, ZZTongActivity.Do_QrCodeTransferClose, param, true, getString(R.string.hint_close_order), 20 * 1000);
    }

    /***
     * Delay 5s to perform get request
     * Requests in less than 2 minutes back if the sale is successful
     */
    private void getTransResult() {
        mHamder.postDelayed(resultRunnable, 5000);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        cancelVolleyRequest(ZZTongActivity.Do_QrCodeTransferClose);
        cancelVolleyRequest(ZZTongActivity.Do_QueryQrCodeTransferResult);
        mHamder.removeCallbacks(resultRunnable);
        mHamder = null;
        super.onDestroy();
    }
}
